package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"repo-manager/cache"
	"repo-manager/model"
	"strconv"
	"time"
)

func Good(c *gin.Context) {
	title := c.PostForm("title")
	count := c.PostForm("count")
	price := c.PostForm("price")
	if title == "" || count == "" || price == "" {
		c.JSON(200, gin.H{

			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Good{

		Title: title,
		Count: count,
		Price: price,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "lsisn" + strconv.Itoa(int(data.ID))

	var article model.Good
	model.DB.Where("id = ?", data.ID).Find(&article)
	Jsonss, _ := json.Marshal(&article)
	cache.Rdb.Set(cache.Ctx, redis_key, Jsonss, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")
	err := model.DB.Where("id = ?", id).Delete(&model.Good{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "lsisn" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func Lists(c *gin.Context) {
	var article []model.Good

	redis_key := "ldsjh"
	cacheDeta, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheDeta == "" {
		model.DB.Find(&article)
		jsonss, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonss, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheDeta), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}
